package cn.db.tools.dbtools.controller;

import cn.db.tools.dbtools.message.ToastMessage;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageConfig;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import javafx.embed.swing.SwingFXUtils;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.DataFormat;
import org.pomo.toasterfx.model.impl.ToastTypes;

import java.awt.image.BufferedImage;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;


/**
 * @author：zooooooooy
 * @date: 2023/8/9 - 18:10
 */
public class QrcodeController implements Initializable {

    @FXML
    private ImageView imageView;

    @FXML
    private TextArea sourceText;

    @FXML
    private Button button;

    // 二维码尺寸
    private static final int QRCODE_SIZE = 300;


    @Override
    public void initialize(URL location, ResourceBundle resources) {

        sourceText.setWrapText(true);
    }

    @FXML
    protected void qrcodeShow() {

        // 二维码配置参数
        MatrixToImageConfig matrixToImageConfig = new MatrixToImageConfig(0xFF002FA7, 0xFFFFFFFF);

        Map<EncodeHintType, Object> hints = new HashMap<>();
        // 设置二维码空白边距为0
        hints.put(EncodeHintType.MARGIN, 0);
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");

        // 生成二维码
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = null;
        try {
            bitMatrix = qrCodeWriter.encode(sourceText.getText(), BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints);
        } catch (WriterException e) {
            throw new RuntimeException(e);
        }

        // 保存二维码
        BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix, matrixToImageConfig);
        WritableImage writableImage = SwingFXUtils.toFXImage(bufferedImage, null);

        imageView.setImage(writableImage);
    }

    @FXML
    protected void copyTextFieldBase64() {
        Clipboard sc = Clipboard.getSystemClipboard();
        ClipboardContent clipboardContent = new ClipboardContent();
        clipboardContent.put(DataFormat.PLAIN_TEXT, sourceText.getText());

        sc.setContent(clipboardContent);
        // 弹出toast消息
        ToastMessage.getInstance().popMessage("复制成功", ToastTypes.SUCCESS);
    }


}
